<template>
  <el-container class="photo-upload">
    <el-main style="overflow-x: hidden;">
      <el-row :gutter="60" justify="center" style="margin-bottom: 5vh">
        <el-col :span="10" class="upload-container">
          <input type="file" ref="leftInput" @change="handleFileChange('left')" hidden />
          <div class="upload-box" @click="handleBoxClick('left', $event)" @drop="handleDrop('left', $event)" @dragover.prevent @dragenter.prevent :class="{ 'has-image': leftImage }">
            <el-image
              v-if="leftImage"
              class="uploaded-image"
              :src="leftImage"
              :preview-src-list="leftPreviewSrcList"
              fit="contain"
              @click="handleImageClick('left')"
              :style="{ width: leftImageWidth + 'px', height: leftImageHeight + 'px' }"
            />
            <p v-else>点击或拖动图片到这里上传</p>
            <div class="delete-btn" v-if="leftImage" @click.stop="deleteImage('left')">✖</div>
          </div>
        </el-col>
        <el-col :span="10" class="upload-container">
          <input type="file" ref="rightInput" @change="handleFileChange('right')" hidden />
          <div class="upload-box" @click="handleBoxClick('right', $event)" @drop="handleDrop('right', $event)" @dragover.prevent @dragenter.prevent :class="{ 'has-image': rightImage }">
            <el-image
              v-if="rightImage"
              class="uploaded-image"
              :src="rightImage"
              :preview-src-list="rightPreviewSrcList"
              fit="contain"
              @click="handleImageClick('right')"
              :style="{ width: rightImageWidth + 'px', height: rightImageHeight + 'px' }"
            />
            <p v-else>点击或拖动图片到这里上传</p>
            <div class="delete-btn" v-if="rightImage" @click.stop="deleteImage('right')">✖</div>
          </div>
        </el-col>
      </el-row>

      
      <div style="height: 10vh; margin-top: 2vh; display: flex;
        justify-content: center;
        align-items: center;">
        <transition name="fade"  style="">
          <!-- <div style="margin-left: 53vh;" class="box" v-if="leftImage && rightImage"  @click="compareImages"> -->
          <div style="border-radius: 5px; padding: 8px 12px; font-size: 16px;cursor: pointer;"
           v-if="leftImage && rightImage" class="box"  @click="compareImages">
            <button class="button" >确定
              <slot></slot>
            </button>
            <div class="matrix">
              <div class="code-line" v-for="i in 10" :key="i" :style="{ '--i': i }">
                <span class="code" v-for="j in 10" :key="j">1</span>
              </div>
            </div>
          </div>
          <!-- <button v-if="leftImage && rightImage" class="compare-button" @click="compareImages">点击比较</button> -->
        </transition>
      </div>
      
    </el-main>
  </el-container>
</template>

<script>
import { ref } from 'vue';
import { useStore } from 'vuex';
import axios from 'axios';
import { ElImage, ElContainer, ElMain, ElRow, ElCol, ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';

export default {
  name: 'PhotoUpload',
  components: {
    ElImage,
    ElContainer,
    ElMain,
    ElRow,
    ElCol
  },
  setup() {
    const store = useStore();

    const leftImage = ref(null);
    const rightImage = ref(null);
    const leftInput = ref(null);
    const rightInput = ref(null);

    const leftPreviewSrcList = ref([]);
    const rightPreviewSrcList = ref([]);

    const leftImageWidth = ref(0);
    const leftImageHeight = ref(0);
    const rightImageWidth = ref(0);
    const rightImageHeight = ref(0);
    const TheOutline = ref('');
    const ThePrediction = ref('');

    const MAX_BOX_WIDTH = 300;
    const MAX_BOX_HEIGHT = 200;

    const Thepoints = ref([]);
    const TheLeftImage = ref('');
    const TheRightImage = ref('');

    const TheALine = ref('____________________________________')

    const isImagePreviewing = ref(false);

    const triggerFileInput = (side) => {
      if (!isImagePreviewing.value) {
        if (side === 'left') {
          leftInput.value.click();
        } else {
          rightInput.value.click();
        }
      }
    };

    const handleFileChange = (side) => {
      const fileInput = side === 'left' ? leftInput.value : rightInput.value;
      if (fileInput.files && fileInput.files[0]) {
        const reader = new FileReader();
        reader.onload = (e) => {
          const img = new Image();
          img.onload = () => {
            const aspectRatio = img.width / img.height;
            if (aspectRatio > MAX_BOX_WIDTH / MAX_BOX_HEIGHT) {
              const width = MAX_BOX_WIDTH;
              const height = MAX_BOX_WIDTH / aspectRatio;
              if (side === 'left') {
                leftImageWidth.value = width;
                leftImageHeight.value = height;
                leftImage.value = e.target.result;
                leftPreviewSrcList.value = [e.target.result];
              } else {
                rightImageWidth.value = width;
                rightImageHeight.value = height;
                rightImage.value = e.target.result;
                rightPreviewSrcList.value = [e.target.result];
              }
            } else {
              const height = MAX_BOX_HEIGHT;
              const width = MAX_BOX_HEIGHT * aspectRatio;
              if (side === 'left') {
                leftImageWidth.value = width;
                leftImageHeight.value = height;
                leftImage.value = e.target.result;
                leftPreviewSrcList.value = [e.target.result];
              } else {
                rightImageWidth.value = width;
                rightImageHeight.value = height;
                rightImage.value = e.target.result;
                rightPreviewSrcList.value = [e.target.result];
              }
            }
          };
          img.src = e.target.result;

        };
        reader.readAsDataURL(fileInput.files[0]);
      }
    };

    const handleDrop = (side, event) => {
      event.preventDefault();
      if (!isImagePreviewing.value) {
        const file = event.dataTransfer.files[0];
        const fileInput = side === 'left' ? leftInput.value : rightInput.value;
        fileInput.files = event.dataTransfer.files;
        handleFileChange(side);
      }
    };

    const handleBoxClick = (side, event) => {
      triggerFileInput(side);
    };

    const deleteImage = (side) => {
      if (side === 'left') {
        leftImage.value = null;
        leftPreviewSrcList.value = [];
      } else {
        rightImage.value = null;
        rightPreviewSrcList.value = [];
      }
      isImagePreviewing.value = false;
    };

    const handleImageClick = (side) => {
      isImagePreviewing.value = true;
    };

    const compareImages = async () => {
      try {
        const formData = new FormData();
        formData.append('now', leftInput.value.files[0]);
        formData.append('before', rightInput.value.files[0]);
        
        const response = await axios.post('http://127.0.0.1:8090/bscnet', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        const data = response.data;

        store.commit('UPDATE_PHOTO_OUTLINE', `http://127.0.0.1:8090/${data.data.outline}`);
        store.commit('UPDATE_PHOTO_PREDICTION', `http://127.0.0.1:8090/${data.data.prediction}`);
        store.commit('SET_POINTS', data.points);

        // 保存左侧和右侧图片的 URL 到 Vuex store
        const leftImageUrl = URL.createObjectURL(leftInput.value.files[0]);
        const rightImageUrl = URL.createObjectURL(rightInput.value.files[0]);
        store.commit('SET_LEFT_IMAGE', leftImageUrl);
        store.commit('SET_RIGHT_IMAGE', rightImageUrl);

        Thepoints.value = store.getters.points;
        TheLeftImage.value = store.getters.leftImage;
        TheRightImage.value = store.getters.rightImage;
        TheOutline.value = store.getters.photoData.outline;
        ThePrediction.value = store.getters.photoData.prediction;
        
        console.log(data.points);
        console.log('网络请求成功');
        // console.log(TheALine.value);
        // console.log('Stored points:', store.getters.points);
        // console.log('Stored leftImage:', store.getters.leftImage);
        // console.log('Stored rightImage:', store.getters.rightImage);
        // console.log('Stored outline:', store.getters.photoData.outline);
        // console.log('Stored prediction:', store.getters.photoData.prediction);
        // console.log(TheALine.value);
        // console.log(Thepoints.value);
        // console.log(TheLeftImage.value);
        // console.log(TheRightImage.value);
        // console.log(TheOutline.value);
        // console.log(ThePrediction.value);
        // console.log(TheALine.value);
        
        // 显示成功消息提示
        ElMessage({
          message: '网络请求成功',
          type: 'success',
          duration: 700, // 自动消失时间，单位为毫秒
          customClass: 'custom-success-message'
        });

      } catch (error) {
        console.error('网络请求失败', error);
        ElMessage({
          message: '网络请求失败',
          type: 'error',
          duration: 700, // 自动消失时间，单位为毫秒
          customClass: 'custom-error-message'
        });
      }
    };

    return {
      leftImage,
      rightImage,
      leftInput,
      rightInput,
      leftPreviewSrcList,
      rightPreviewSrcList,
      leftImageWidth,
      leftImageHeight,
      rightImageWidth,
      rightImageHeight,
      triggerFileInput,
      handleFileChange,
      handleDrop,
      handleBoxClick,
      deleteImage,
      compareImages,
      Thepoints,
      TheLeftImage,
      TheRightImage,
      TheOutline,
      ThePrediction,
      TheALine,
      handleImageClick,
      isImagePreviewing,
    };
  }
};
</script>

<style scoped>
.photo-upload {
  height: 95vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.upload-container {
  text-align: center;
  display: flex;
  justify-content: center;
}

.upload-box {
  border: 2px dashed #cccccc;
  padding: 20px;
  cursor: pointer;
  position: relative;
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
  position: relative;
  width: 100%;
  max-width: 300px;
  height: 100%;
  max-height: 200px;
}

.upload-box:hover {
  border-color: #999999;
}

.upload-box.has-image {
  border: none;
}

.uploaded-image {
  object-fit: contain;
}

.compare-button {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.compare-button:hover {
  background-color: #0056b3;
}

.delete-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.delete-btn:hover {
  background-color: rgba(0, 0, 0, 0.7);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 自定义消息提示样式 */
.custom-success-message .el-message__content {
  background-color: #e0f7fa; /* 浅蓝色背景 */
  color: #00796b; /* 浅蓝色文字 */
}
.custom-error-message .el-message__content {
  background-color: #ffebee; /* 浅红色背景 */
  color: #d32f2f; /* 浅红色文字 */
}





.outer-container {
  display: flex;
  justify-content: center;
  align-items: center;
  /* height: 100vh; 使外部容器全屏高度，以便内容居中 */
}

.box {
  --clr-shadow__border: #A8DF8E;
  --clr-text: #F6F4EB;
  --clr-code-line: #43ff85;
  --clr-matrix: #020204;
  --size: 3rem;
  position: relative;
  outline: 1px solid var(--clr-shadow__border);
  height: 4vh;
  width: 12vh;
  border-radius: 1vh; /* 设置圆角 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.button {
  font-weight: 600;
  font-size: 0.85rem; /* 调整字体大小以适应较小的按钮 */
  letter-spacing: 0.1rem; /* 调整字母间距 */
  color: var(--clr-text);
  padding: calc(var(--size) / 6) calc(var(--size) / 2); /* 调整按钮的内边距 */
  background: transparent;
  border: none;
  cursor: pointer;
  text-shadow: 1px 0px var(--clr-shadow__border), 0px 1px var(--clr-shadow__border),
               -1px 0px var(--clr-shadow__border), 0px -1px var(--clr-shadow__border); /* 调整阴影效果 */
}

.matrix {
  width: 100%;
  height: 100%;
  bottom: 0;
  transition: 0.5s ease-in-out;
  z-index: -1;
  opacity: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: absolute;
  background: var(--clr-matrix);
  border-radius: 1vh; /* 使背景也有圆角 */
}

.box:hover .matrix {
  opacity: 1;
}

.code-line {
  position: relative;
  display: flex;
  flex-direction: column-reverse;
  transition: 0.5s;
  min-height: 0.3rem; /* 调整最小高度 */
  min-width: 0.3rem;  /* 调整最小宽度 */
  animation: matrix-animation calc(.6s * var(--i)) linear infinite;
}

.code {
  text-shadow: 10px 50px var(--clr-code-line), -10px -25px var(--clr-code-line); /* 调整阴影效果 */
  font-size: 0.9rem; /* 调整字体大小 */
  font-weight: 400;
  color: var(--clr-code-line);
  opacity: 0.5;
}

.code:first-child {
  color: var(--clr-text);
  opacity: 1;
}

@keyframes matrix-animation {
  0% {
    transform: translateY(calc(-50% * var(--i)));
  }

  100% {
    transform: translateY(calc(50% * var(--i)));
  }
}
</style>